package cn.yanjr.system.action;

import java.io.IOException;
import java.net.InetAddress;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;

import com.alibaba.fastjson.JSON;

import cn.yanjr.common.Constant;
import cn.yanjr.common.CurrentInfoUtil;
import cn.yanjr.common.bean.BeanFactory;
import cn.yanjr.common.cache.CacheManager;
import cn.yanjr.common.enums.ResultEnums;
import cn.yanjr.common.utils.JwtUtil;
import cn.yanjr.common.utils.Login;
import cn.yanjr.common.utils.Md5Util;
import cn.yanjr.common.utils.Result;
import cn.yanjr.common.web.BaseServlet;
import cn.yanjr.system.entity.SysMenu;
import cn.yanjr.system.entity.SysRole;
import cn.yanjr.system.entity.SysUser;
import cn.yanjr.system.service.SysRoleService;
import cn.yanjr.system.service.SysUserService;

@WebServlet("/login/*")
public class LoginServlet extends BaseServlet{
	Logger logger= Logger.getLogger(LoginServlet.class);
	/**
	 * 
	 */
	private static final long serialVersionUID = 4060984362128007158L;
	private SysUserService sysUserService = BeanFactory.getBean("sysUserService", SysUserService.class);
	private SysRoleService sysRoleService = BeanFactory.getBean("sysRoleService", SysRoleService.class);

	
	@SuppressWarnings("unchecked")
	public void sign(HttpServletRequest request, HttpServletResponse response) 
			throws IOException, ServletException {
		Map<String, Object> result = new HashMap<String, Object>();
		
		String loginName = request.getParameter("loginName");
		String password = request.getParameter("password");
		SysUser user =  sysUserService.getUserByLoginName(loginName);
		if(user != null) {
			String p = Md5Util.md5(password);
			p = p + p.substring(0, 2);
			p = Md5Util.md5(p);
			if(p.equals(user.getPassword())) {
				CacheManager.put("user_" + user.getId(), user);
				int statusId = 1;//正式服务器
				try {
					String ip = InetAddress.getLocalHost().getHostAddress();
					logger.info("server ip : " + ip);
					if(!Constant.SERVER_IP.equals(ip)) {
						statusId = 2;//开发测试
					}
				} catch (Exception e) {
					e.printStackTrace();
				}
				
				Map<String, Object> param = new HashMap<String, Object>();
				param.put("userId", user.getId());
				param.put("statusId", statusId);
				Map<String, Object> map = sysUserService.userMenus(param);
				List<SysMenu> list = (List<SysMenu>) map.get("list");
				CacheManager.put("userMenus_" + user.getId(), list);
				
				Map<String, SysMenu> pathMenuMap = new HashMap<String, SysMenu>();
				Map<String, SysMenu> buttMenuMap = new HashMap<String, SysMenu>();
				for(SysMenu m : list) {
					if(m.getIsShow() == 0) {
						buttMenuMap.put(m.getPermission(), m);
					} else {
						if(StringUtils.isNotEmpty(m.getHref())) {
							pathMenuMap.put(m.getHref(), m);
						}
					}
				}
				CacheManager.put("buttMenuMap_" + user.getId(), buttMenuMap);
				CacheManager.put("pathMenuMap_" + user.getId(), pathMenuMap);
				
				//获取数据权限等级
				List<SysRole> roleList = sysRoleService.getUserRoles(user.getId());
				int dataScope = 0;
				if(roleList != null && roleList.size() > 0) {
					for(SysRole role : roleList) {
						if(Integer.parseInt(role.getDataScope()) > dataScope) {
							dataScope = Integer.parseInt(role.getDataScope());
						}
					}
				}
				CacheManager.put("dataScope_" + user.getId(), dataScope);
				CacheManager.put("userDataScope_" + user.getId(), userDataScope(dataScope, user));
				
				//生成jwtToken
				Login login = new Login();
				login.setId(user.getId());
				login.setPassword(password);
				login.setLoginName(loginName);
				String jwtToken = JwtUtil.sign(login);
				
				result.put("loginId", user.getId());
				result.put("token", jwtToken);
				result.put("path", "/overlay/index");
				
				logger.info(JSON.toJSONString(result));
				CurrentInfoUtil.responsePrint(response, Result.success(result));
			} else {
				CurrentInfoUtil.responsePrint(response, Result.error(ResultEnums.PASSWORD_ERROR));
			}
		} else {
			CurrentInfoUtil.responsePrint(response, Result.error(ResultEnums.USERNAME_NOT_EXIST));
		}
		
	}
	
	
	
	
	
	
	
	
	public String userDataScope(int dataScope, SysUser user) {
		String string = "";
		StringBuilder scope = new StringBuilder();
		List<SysUser> list = null;
		if(dataScope == 4) {//所在部门及以下数据
			list = sysUserService.getUserByOfficeAndChild(user.getOfficeId());
		} else if(dataScope == 5) {//所在部门数据
			list = sysUserService.getUserByOffice(user.getOfficeId());
		} else if(dataScope == 8) {//仅本人数据
			scope.append(",'").append(user.getId()).append("'");
		}
		if(list != null && list.size() > 0) {
			for(SysUser u : list) {
				scope.append(",'").append(u.getId()).append("'");
			}
		}
		string = scope.toString();
		if(string.length() > 0) {
			string = string.substring(1);
		}
		return string;
	}
}
